package com.example.aircraftwar.codes.basic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.View;

import com.example.aircraftwar.codes.activity.GameActivity;

public class GameBackground extends View {
    Context context;
    /**
     * 图片
     */
    private final Bitmap background;

    /**
     * x 轴长度，根据图片尺寸获得
     * -1 表示未设置
     */

    public void setBackGroundTop(int backGroundTop) {
        this.backGroundTop = backGroundTop;
    }

    private int backGroundTop;

    public GameBackground(Context context, Bitmap background) {
        super(context);
        this.context = context;
        this.background = background;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Bitmap background = getImage();
        canvas.drawBitmap(background, 0, backGroundTop, new Paint());
        if (backGroundTop == 0) {
            return;
        }
        @SuppressLint("DrawAllocation")
        Bitmap background0 = Bitmap.createBitmap(background,
                0,
                GameActivity.WINDOW_HEIGHT - backGroundTop,
                GameActivity.WINDOW_WIDTH,
                backGroundTop);

        canvas.drawBitmap(background0, 0, 0, new Paint());

    }

    public Bitmap getImage() {
        return imageScale(background, GameActivity.WINDOW_WIDTH, GameActivity.WINDOW_HEIGHT);
    }

    /**
     * 调整图片大小
     *
     * @param bitmap 源
     * @param dst_w  输出宽度
     * @param dst_h  输出高度
     * @return Bitmap
     */
    private Bitmap imageScale(Bitmap bitmap, int dst_w, int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        Matrix matrix = new Matrix();
        matrix.postScale(scale_w, scale_h);
        return Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                true);
    }

}
